package com.tencent.qf.systembiz.service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.tencent.qf.common.pojo.OperateLogVO;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import com.tencent.qf.system.api.OperateLogApi;
import com.tencent.qf.system.api.log.OperateLogDTO;
import com.tencent.qf.systembiz.controller.request.OperateLogListReqVo;
import com.tencent.qf.systembiz.convert.SystemConvert;
import com.tencent.qf.systembiz.dal.OperateLogDO;
import com.tencent.qf.systembiz.dal.OperateLogExample;
import com.tencent.qf.systembiz.dao.OperateLogDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

/**
 * Copyright (C) 2022 Limited, a Tencent company. All rights reserved.
 * 操作日志
 *
 * @author p_htaozhou@tencent.com
 * @create: 2022/9/13 15:40
 */
@Service
@Slf4j
public class OperateLogService implements OperateLogApi {
    @Resource
    private OperateLogDao operateLogDao;

    @Override
    public Boolean createOperateLog(OperateLogDTO operateLogDTO) {
        return operateLogDao.insertSelective(SystemConvert.INSTANCE.operateLogDTO2DO(operateLogDTO)) > 0;
    }

    public PageResult<OperateLogVO> getOperateLogList(PageRequest<OperateLogListReqVo> request) {
        OperateLogExample example = new OperateLogExample();
        example.setLimit(request.getPageSize());
        example.setOffset((request.getPageNo() - 1) * request.getPageSize());
        String traceId = request.getData().getTraceId();
        String module = request.getData().getModule();
        OperateLogExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(traceId)) {
            criteria.andTraceIdEqualTo(request.getData().getTraceId());
        }
        if (!StringUtils.isEmpty(module)) {
            criteria.andModuleEqualTo(request.getData().getModule());
        }
        List<OperateLogDO> operateLogDOList = operateLogDao.selectByExample(example);
        log.info("OperateLogService.getOperateLogList errorLogDao response: {}", JSON.toJSONString(operateLogDOList));

        PageResult<OperateLogVO> pageResult = new PageResult<>();
        pageResult.setList(operateLogDOList.stream().map(SystemConvert.INSTANCE::operateLogDO2VO).collect(Collectors.toList()));
        long total = operateLogDao.countByExample(example);
        pageResult.setTotal(total);
        pageResult.setPageSize(request.getPageSize());
        pageResult.setPage(request.getPageNo());

        return pageResult;
    }
}
